clear all;
close all;
clc;

rng;

N = 100000;

% uniform
a = 10;
b = 22;
x = a+(b-a).*rand(1, N);

bins = (a-2):0.1:(b+2);
[yh, xh] = hist(x, bins);

figure;
subplot(2,1,1);
hist(x, bins);
hold on;
plot(xh, yh, 'r', 'LineWidth', 3);

dxh = xh(2)-xh(1);
ph = yh / (sum(yh) * dxh);
%[nul, i1, i2] = intersect(bins, xh);
%tmp = zeros(1,length(bins));
%tmp(i1) = ph;
%ph = tmp;
%xh = bins;

subplot(2,1,2)
plot(xh, ph, 'r', 'LineWidth', 3);
xlabel('X');
ylabel('P(X)');

% Gauss N(16,0.2)
m = 0;
sigma = 2;
bins = (m-6*sigma):0.1:(m+6*sigma);
x2 = m + sigma*randn(1,N);
x3 = m + sigma*randn(1,N);

x4 = sqrt(x2 .^ 2 + x3 .^ 2);

[yh2, xh2] = hist(x2, bins);

figure;
subplot(2,1,1);
hist(x2, bins);
hold on;
plot(xh2, yh2, 'r', 'LineWidth', 3);

dxh2 = xh2(2)-xh2(1);
ph2 = yh2 / (sum(yh2) * dxh2);

subplot(2,1,2)
plot(xh2, ph2, 'r', 'LineWidth', 3);
xlabel('X');
ylabel('P(X)');

% Hi^2 распределение релея:2
figure;
bins = (m-6*sigma):0.1:(m+6*sigma);
[yh4, xh4] = hist(x4, 110);
subplot(2,1,1);
hist(x4, 110);
hold on;
plot(xh4, yh4, 'r', 'LineWidth', 3);

dxh4 = xh4(2)-xh4(1);
ph4 = yh4 / (sum(yh4) * dxh4);

subplot(2,1,2)
plot(xh4, ph4, 'r', 'LineWidth', 3);
xlabel('X');
ylabel('P(X)');

% dependent variable value
Mx = 3;
My = 4;
Mz = 5; %= [3, 4, 5];
Dx = 16;
Dy = 16;
Dz = 16;
Dxy = 12;
Dyz = 12;
Dxz = 8;

L = chol([Dx  Dxy Dxz;
          Dxy Dy  Dyz;
          Dxz Dyz Dz]);
      
X = nan(1,N);
Y = nan(1,N);
Z = nan(1,N);

for i = 1:N
   Ng = L * randn(3,1);
   X(i) = Mx + Ng(1);
   Y(i) = My + Ng(2);
   Z(i) = Mz + Ng(3);
end
      
hist(X);
hist(Y);
hist(Z);